<?php
/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/12/29
 * Time: 13:27
 */

namespace App\Services;


use App\Models\Advice;
use App\Models\Contest;
use App\Models\Department;
use App\Models\GrowRule;
use App\Models\IncreaseScoreApply;
use App\Models\Manager;
use App\Models\MemberFileScore;
use App\Models\ScoreFile;
use App\Models\User;
use App\Models\UserLevel;
use Illuminate\Support\Facades\Redis;

class DepartmentService extends Service
{
    public static function getDepartmentId($managerId)
    {
        $cacheKey = sprintf('pt:department:mid:%d', $managerId);
        $cacheData = Redis::get($cacheKey);
        if (!$cacheData) {
            $manager = Manager::where('id', $managerId)->first();
            $cacheData = $manager->department_id;
            Redis::setex($cacheKey, 7200, $cacheData);
        }
        return $cacheData;
    }

    public static function getScoreFile($departmentId, $year)
    {
        $next = $year + 1;
        $query = ScoreFile::where('is_del', 0)->where('type', 2)->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00');
        $total = $query->count();
        $files = $query->get();
        $result = [];
        $n = 0;
        foreach ($files as $file) {
            $n ++;
            $fileScore = MemberFileScore::where('score_file_id', $file->id)->where('type', 1)->where('department_id', $departmentId)->first();
            $fileScore2 = MemberFileScore::where('score_file_id', $file->id)->where('type', 3)->where('department_id', $departmentId)->first();
            $result[] = [
                'id' => $n,
                'score_file_id' => $file->id,
                'content' => $file->content,
                'self_score' => $fileScore ? $fileScore->score : 0,
                'score' => $fileScore2 ? $fileScore2->score : 0
            ];
        }
        $increases = IncreaseScoreApply::where('is_del', 0)->where('department_id', $departmentId)->where('role', 2)->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00')->get();
        $score = 0;
        foreach ($increases as $increase) {
            $score += $increase->score;
        }
        $result[] = [
            'id' => 0,
            'content' => '加分中心累计分数: '.$score,
            'score' => $score
        ];
        return [
            'total' => $total,
            'rows' => $result,
            'limit' => 10,
            'offset' => 0,
            'page' => ceil($total / 10),
            'pageNumber' => 1
        ];
    }

    public static function deleteIncreaseScore($id)
    {
        $increaseScore = IncreaseScoreApply::where('id', $id)->first();
        if ($increaseScore) {
            $increaseScore->is_del = 1;
            $increaseScore->updated_at = date('Y-m-d H:i:s', time());
            $increaseScore->save();
        }
    }

    public static function getUserScoreFile($departmentId, $uid)
    {
        $user = User::where('id', $uid)->first();
        $year = date('Y', time());
        $next = $year + 1;
        $query = ScoreFile::where('is_del', 0)->where('type', 1)->where('created_at', '>=', $year.'-01-01 00:00:00');
        if ($user->role == 5) {
            $query->where('role', 5);
        } else {
            $query->where('role', 1);
        }
        $total = $query->count();
        $files = $query->get();
        $results = [];
        $n = 0;
        foreach ($files as $file) {
            $n ++;
            $fileScores = MemberFileScore::where('score_file_id', $file->id)->where('user_id', $uid)->where('role', 1)->get();
            $score = $selfScore = $juniorScore = 0;
            foreach ($fileScores as $fileScore) {
                if ($fileScore->type == 1 && $fileScore->department_id == 0 && $fileScore->role == 1) {
                    $selfScore = $fileScore->score;
                }
                if ($fileScore->type == 2 && $fileScore->department_id == $departmentId && $fileScore->role == 1) {
                    $juniorScore = $fileScore->score;
                }
                if ($fileScore->type == 3 && $fileScore->department_id == 0 && $fileScore->role == 1) {
                    $score = $fileScore->score;
                }
            }
            $results[] = [
                'id' => $n,
                'score_file_id' => $file->id,
                'content' => $file->content,
                'score' => $score,
                'self_score' => $selfScore,
                'junior_score' => $juniorScore
            ];
        }
        $increases = IncreaseScoreApply::where('is_del', 0)->where('user_id', $uid)->where('department_id', $departmentId)->where('role', 1)->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00')->get();
        $score = 0;
        foreach ($increases as $increase) {
            $score += $increase->score;
        }
        $results[] = [
            'id' => 0,
            'content' => '加分中心累计分数: '.$score,
            'score' => $score
        ];
        return [
            'total' => $total,
            'rows' => $results,
            'limit' => 10,
            'offset' => 0,
            'page' => ceil($total / 10),
            'pageNumber' => 1
        ];
    }

    public static function getUserScoreFileDetail($id, $departmentId, $uid)
    {
        $file = ScoreFile::where('id', $id)->first();
        $fileScore = MemberFileScore::where('score_file_id', $file->id)->where('type', 2)->where('department_id', $departmentId)->where('user_id', $uid)->where('role', 1)->first();
        return [
            'id' => $file->id,
            'title' => $file->title,
            'content' => $file->content,
            'refer_score' => $file->score,
            'score' => $fileScore ? $fileScore->score : 0
        ];
    }

    public static function getScoreFileDetail($id, $departmentId)
    {
        $file = ScoreFile::where('id', $id)->first();
        $fileScore = MemberFileScore::where('score_file_id', $file->id)->where('type', 1)->where('department_id', $departmentId)->where('role', 2)->first();
        return [
            'id' => $file->id,
            'title' => $file->title,
            'content' => $file->content,
            'refer_score' => $file->score,
            'score' => $fileScore ? $fileScore->score : 0
        ];
    }

    public static function saveScoreFileScore($id, $departmentId, $score)
    {
        $file = ScoreFile::where('id', $id)->first();
        $fileScore = MemberFileScore::where('score_file_id', $file->id)->where('type', 1)->where('department_id', $departmentId)->where('role', 2)->first();
        if (!$fileScore) {
            $fileScore = new MemberFileScore();
            $fileScore->score_file_id = $file->id;
            $fileScore->type = 1;
            $fileScore->department_id = $departmentId;
            $fileScore->role = 2;
            $fileScore->created_at = date('Y-m-d H:i:s', time());
        }
        $fileScore->score = $score;
        $fileScore->updated_at = date('Y-m-d H:i:s', time());
        $fileScore->save();
    }

    public static function saveUserScoreFileScore($id, $departmentId, $uid, $score)
    {
        $file = ScoreFile::where('id', $id)->first();
        $fileScore = MemberFileScore::where('score_file_id', $file->id)->where('type', 2)->where('department_id', $departmentId)->where('user_id', $uid)->where('role', 1)->first();
        if (!$fileScore) {
            $fileScore = new MemberFileScore();
            $fileScore->score_file_id = $file->id;
            $fileScore->type = 2;
            $fileScore->department_id = $departmentId;
            $fileScore->user_id = $uid;
            $fileScore->role = 1;
            $fileScore->created_at = date('Y-m-d H:i:s', time());
        }
        $fileScore->score = $score;
        $fileScore->updated_at = date('Y-m-d H:i:s', time());
        $fileScore->save();
    }



    public static function getIncreaseScore($departmentId, $limit, $offset, $search = '')
    {
        $department = Department::where('id', $departmentId)->first();
        $query = IncreaseScoreApply::where('is_del', 0)->where('department_id', $departmentId)->where('role', 2);
        if ($search) {
            $query->where('title', 'like', "%{$search}%");
        }$total = $query->count();
        $increases = $query->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        $result = [];
        foreach ($increases as $increase) {
            $result[] = [
                'id' => $increase->id,
                'title' => $increase->title,
                'created_at' => date('Y-m-d H:i:s', strtotime($increase->created_at)),
                'name' => $department->name,
                'score' => $increase->score
            ];
        }
        return [
            'total' => $total,
            'rows' => $result,
            'pages' => ceil($total / $limit),
            'page' => $offset / $limit + 1

        ];
    }

    public static function getSimple()
    {
        $departments = Department::where('is_del', 0)->get();
        $result = [];
        foreach ($departments as $department) {
            $result[] = [
                'id' => $department->id,
                'name' => $department->name
            ];
        }

        return $result;
    }

    public static function getDetail($id)
    {
        $department = Department::where('is_del', 0)->where('id', $id)->first();
        if (!$department) {
            return [];
        }

        $members = [];
        $users = User::where('is_del', 0)->where('department_id', $id)->orderBy('id', 'desc')->limit(5)->get();
        foreach ($users as $user) {
            $members[] = [
                'id' => $user->id,
                'realname' => $user->realname
            ];
        }
        $year = date('Y', time());
        $score = 0;
        $applyScores = IncreaseScoreApply::where('is_del', 0)->where('role', 2)->where('department_id', $id)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
        foreach ($applyScores as $applyScore) {
            $score += $applyScore->score;
        }
        $memberScoreFiles = MemberFileScore::where('is_del', 0)->where('role', 2)->where('type', 3)->where('department_id', $id)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
        foreach ($memberScoreFiles as $memberScoreFile) {
            $score += $memberScoreFile->score;
        }
        return [
            'id' => $department->id,
            'name' => $department->name,
            'found_at' => date('Y-m-d', strtotime($department->found_at)),
            'members' => $members,
            'score' => $score,
            'desc' => $department->desc,
            'summary' => $department->summary
        ];
    }

    public static function delete($id)
    {
        $department = Department::where('is_del', 0)->where('id', $id)->first();
        $department->is_del = 1;
        $department->updated_at = date('Y-m-d H:i:s', time());
        $department->save();
    }

    public static function getSimpleUsers($departmentId)
    {
        $users = User::where('is_del', 0)->where('department_id', $departmentId)->orderBy('id', 'desc')->get();
        $result = [];
        foreach ($users as $user) {
            $result[] = [
                'id' => $user->id,
                'realname' => $user->realname
            ];
        }
        return $result;
    }

    public static function getUsersByDepartmentId($departmentId, $limit, $offset, $role = 0, $search = '')
    {
        $year = date('Y', time());
        $query = User::where('is_del', 0)->where('department_id', $departmentId);
        if ($role > 0) {
            $query = $query->where('role', $role);
        }
        if ($search) {
            $query = $query->where('realname', 'like', "%{$search}%");
        }
        $total = $query->count();
        $users = $query->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        $department = Department::where('id', $departmentId)->first();
        $result = [];
        foreach ($users as $user) {
            $score = 0;
            $applyScores = IncreaseScoreApply::where('is_del', 0)->where('role', 1)->where('user_id', $user->id)->where('department_id', $departmentId)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
            foreach ($applyScores as $applyScore) {
                $score += $applyScore->score;
            }
            $memberScoreFiles = MemberFileScore::where('is_del', 0)->where('role', 1)->where('type', 3)->where('user_id', $user->id)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
            foreach ($memberScoreFiles as $memberScoreFile) {
                $score += $memberScoreFile->score*0.9;
            }
            $result[] = [
                'id' => $user->id,
                'realname' => $user->realname,
                'department_id' => $user->department_id,
                'department_name' => $department ? $department->name : '',
                'score' => $score,
                'role' => $user->role,
                'level' => self::getUserYearLevel($user->id, $year)
            ];
        }
        return [
            'total' => $total,
            'rows' => $result,
            'pages' => ceil($total / $limit),
            'page' => $offset / $limit + 1

        ];
    }

    public static function save($data)
    {
        if (array_key_exists('id', $data)) {
            $department = Department::where('id', $data['id'])->first();
        } else {
            $department = new Department();
            $department->created_at = date('Y-m-d H:i:s', time());
        }
        foreach ($data as $key => $value) {
            $department->$key = $value;
        }
        $department->updated_at = date('Y-m-d H:i:s', time());
        $department->save();
    }

    public static function saveIncreaseScore($departmentId, $data)
    {
        if (array_key_exists('id', $data)) {
            $increase = IncreaseScoreApply::where('id', $data['id'])->first();
        } else {
            $increase = new IncreaseScoreApply();
            $increase->created_at = date('Y-m-d H:i:s', time());
        }
        $increase->user_id = 0;
        $increase->department_id = $departmentId;
        foreach ($data as $key => $value) {
            $increase->$key = $value;
        }
        $increase->score = 0;
        $increase->updated_at = date('Y-m-d H:i:s', time());
        $increase->save();
    }

    public static function saveUserIncrease($id, $departmentId, $score)
    {
        $increase = IncreaseScoreApply::where('id', $id)->first();
        $increase->department_id = $departmentId;
        $increase->score = $score;
        $increase->updated_at = date('Y-m-d H:i:s', time());
        $increase->save();
    }

    public static function getLastRule()
    {
        $rule = GrowRule::where('is_del', 0)->where('type', 2)->orderBy('id', 'desc')->first();
        if (!$rule) {
            return [];
        }

        return [
            'id' => $rule->id,
            'title' => $rule->title,
            'content' => $rule->content
        ];
    }

    public static function getLastAdvice($departmentId)
    {
        $advice = Advice::where('is_del', 0)->where('department_id', $departmentId)->where('type', 2)->orderBy('id', 'desc')->first();
        if (!$advice) {
            return [];
        }

        return [
            'id' => $advice->id,
            'created_at' => date('Y-m-d H:i:s', strtotime($advice->created_at)),
            'content' => $advice->content
        ];
    }

    public static function deleteContest($id)
    {
        $contest = Contest::where('is_del', 0)->where('id', $id)->where('type', 1)->first();
        if (!$contest) return;
        $contest->is_del = 1;
        $contest->updated_at = date('Y-m-d H:i:s', time());
        $contest->save();
    }

    public static function saveContest($data)
    {
        if (array_key_exists('id', $data)) {
            $contest = Contest::where('id', $data['id'])->first();
        } else {
            $contest = new Contest();
            $contest->type = 1;
            $contest->created_at = date('Y-m-d H:i:s', time());
        }
        foreach ($data as $key => $value) {
            $contest->$key = $value;
        }
        $contest->updated_at = date('Y-m-d H:i:s', time());
        $contest->save();
    }

    public static function getUserDetail($id)
    {
        $year = date('Y', time());
        $user = User::where('id', $id)->where('is_del', 0)->first();
        if (!$user) return [];
        $department = Department::where('is_del', 0)->where('id', $user->department_id)->first();
        $departmentName = $department ? $department->name : '';
        $score = 0;
        if ($department) {
            $applyScores = IncreaseScoreApply::where('is_del', 0)->where('role', 1)->where('user_id', $id)->where('department_id', $department->id)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
            foreach ($applyScores as $applyScore) {
                $score += $applyScore->score;
            }
            $memberScoreFiles = MemberFileScore::where('is_del', 0)->where('role', 1)->where('type', 3)->where('user_id', $id)->where('created_at', '>=', $year.'-01-01 00:00:00')->get();
            foreach ($memberScoreFiles as $memberScoreFile) {
                $score += $memberScoreFile->score*0.9;
            }
        }
        return [
            'id' => $user->id,
            'number' => $user->number,
            'realname' => $user->realname,
            'gender' => gender($user->gender),
            'birthday' => date('Y-m-d', strtotime($user->birthday)),
            'join_party_at' => date('Y-m-d', strtotime($user->join_party_at)),
            'mobile' => $user->mobile,
            'role' => $user->role,
            'role_name' => get_role_name($user->role),
            'education_code' => $user->education_code,
            'education_name' => education($user->education_code),
            'department_id' => $user->department_id,
            'department_name' => $departmentName,
            'score' => $score,
            'summary' => $user->summary,
            'level' => self::getUserYearLevel($id, $year)
        ];
    }

    public static function deleteUser($id)
    {
        $user = User::where('id', $id)->first();
        $user->is_del = 1;
        $user->updated_at = date('Y-m-d H:i:s', time());
        $user->save();
    }

    public static function adviceToUser($uid, $limit, $offset, $departmentId, $year = 0)
    {
        $query = Advice::where('is_del', 0)->where('user_id', $uid)->where('department_id', $departmentId)->where('type', 1);
        if ($year > 0) {
            $next = $year + 1;
            $query->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00');
        }
        $total = $query->count();
        $advices = $query->orderBy('id', 'desc')->limit($limit)->offset($offset)->get();
        $department = Department::where('is_del', 0)->where('id', $departmentId)->first();
        $result = [];
        foreach ($advices as $advice) {

            $result[] = [
                'department_name' => $department->name,
                'created_at' => date('Y-m-d H:i:s', strtotime($advice->created_at)),
                'content' => $advice->content
            ];
        }
        return [
            'total' => $total,
            'rows' => $result,
            'pages' => ceil($total / $limit),
            'page' => $offset / $limit + 1

        ];
    }

    public static function saveAdvice($uid, $departmentId, $content)
    {
        $advice = new Advice();
        $advice->user_id = $uid;
        $advice->department_id = $departmentId;
        $advice->type = 1;
        $advice->content = $content;
        $advice->created_at = date('Y-m-d H:i:s', time());
        $advice->updated_at = date('Y-m-d H:i:s', time());
        $advice->save();
    }

    public static function getUserLevel($uid, $departmentId)
    {
        $year = date('Y', time());
        $next = $year + 1;
        $selfLevel = UserLevel::where('user_id', $uid)->where('department_id', 0)->where('type', 1)->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00')->first();
        $juniorLevel = UserLevel::where('user_id', $uid)->where('department_id', $departmentId)->where('type', 2)->where('created_at', '>=', $year.'-01-01 00:00:00')->where('created_at', '<', $next.'-01-01 00:00:00')->first();
        return [
            'self_level' => $selfLevel ? ['id' => $selfLevel->id, 'level' => $selfLevel->level] : ['id' => 0, 'levle' => 0],
            'junior_level' => $juniorLevel ? ['id' => $juniorLevel->id, 'level' => $juniorLevel->level] : ['id' => 0, 'levle' => 0]
        ];
    }

    public static function saveUserLevel($data, $departmentId)
    {
        if (array_key_exists('id', $data)) {
            $level = UserLevel::where('id', $data['id'])->first();
        } else {
            $level = new UserLevel();
            $level->user_id = $data['user_id'];
            $level->department_id = $departmentId;
            $level->type = 2;
            $level->created_at = date('Y-m-d H:i:s', time());
        }
        $level->level = $data['level'];
        $level->updated_at = date('Y-m-d H:i:s', time());
        $level->save();
    }
}